package com.fishery.authority.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.authority.entity.Function;
import com.fishery.authority.entity.FunctionParent;
import com.fishery.authority.service.FunctionService;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 711
 * @since 2021-01-13
 */
@Api(description = "权限管理模块")
@RestController
@CrossOrigin
@RequestMapping("/function")
public class FunctionController {
    @Autowired
    private FunctionService functionService;

    /**
     * 查询全部权限
     *
     * @return
     */
    @ApiOperation(value = "查询所有权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @GetMapping
    public Result indexAllPermission() {
        List<FunctionParent> list = functionService.grand(functionService.queryAllFunction());
        return Result.success().data(list);
    }

    /**
     * 分页查询所有权限
     *
     * @param current
     * @param size
     * @return
     */
    @ApiOperation(value = "分页查询所有权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @GetMapping("/search/{current}/{size}")
    public Result indexAllPermissionPage(@PathVariable int current,
                                         @PathVariable int size) {
        size = size <= 0 ? 5 : size;
        current = current <= 0 ? 1 : current;
        Page<Function> page = new Page(current, size);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("parentId");
        functionService.page(page, wrapper);
        return Result.success().data(page);
    }

    /**
     * 根据ID查询
     * @param id ID
     * @return
     */
    @ApiOperation("根据权限Id查找权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value="/{id}",method= RequestMethod.GET)
    public Result findById(@PathVariable String id){
        return new Result(true,StatusCode.OK,"查询成功",functionService.findById(id));
    }



    /**
     * 根据id列表删除权限
     *
     * @param idList
     * @return
     */
    @ApiOperation(value = "根据id列表删除权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @DeleteMapping("/batchRemove")
    public Result remove(@RequestBody List<String> idList) {
        boolean result = functionService.removeByIds(idList);
        return result ? Result.success() : Result.error();
    }

//    /**
//     * 给角色分配权限
//     *
//     * @param roleId
//     * @param functionId
//     * @return
//     */
//    @ApiOperation(value = "给角色分配权限")
//    @PostMapping("/doAssign")
//    public Result doAssign(String roleId,String[] functionId) {
//        if (StringUtils.isEmpty(roleId)) {
//            return Result.error();
//        }
//        functionService.saveRoleFunction(roleId,functionId);
//        return Result.success();
//    }

    /**
     * 新增权限
     *
     * @param function
     * @return
     */
    @ApiOperation(value = "新增权限")
    @PostMapping("/save")
    public Result save(@RequestBody Function function) {
        if (function == null) {
            return Result.error();
        }
        boolean result = functionService.save(function);
        return result ? Result.success() : Result.error();
    }

    /**
     * 修改权限
     * @param function
     * @return
     */
    @ApiOperation(value = "修改权限")
    @PutMapping("/update")
    public Result updateById(@RequestBody Function function) {
        if (function == null || StringUtils.isEmpty(function.getId())) {
            return Result.error();
        }
        boolean result = functionService.updateById(function);
        return result ? Result.success() : Result.error();
    }

    //基地老板更新基地角色的权限
    /**
     * 基地老板更新基地角色的权限
     * @param baseId
     * @param baseIdentity
     * @param functionIdList
     * @return
     */
    @ApiOperation("基地老板更新基地角色的权限")
    @PreAuthorize("hasAnyAuthority('authority_role_updateRoleFunction')")
    @RequestMapping(value="/base/{baseId}/{baseIdentity}",method = RequestMethod.PUT)
    public Result UpdateFunOfRole(@PathVariable String baseId,
                                  @PathVariable Integer baseIdentity,
                                  @RequestBody
                                      @ApiParam(name = "权限Id集合Map", value = "传入json格式,{\"functionIdList\": [\"1\", \"3\"]}")
                                              Map functionIdList)
    {
        functionService.UpdateBaseFunOfRole(baseId, baseIdentity, functionIdList);
        return new Result(true,StatusCode.OK,"更新角色权限成功", null);
    }

    /**
     * 根据基地id和基地身份查询基地用户权限
     *
     * @param baseId
     * @param baseIdentity
     * @return
     */
    @ApiOperation("根据基地id和基地身份查询角色权限")
    @RequestMapping(value="/{baseId}/{baseIdentity}",method = RequestMethod.GET)
    public Result findBaseFunctionByBase(@PathVariable String baseId,
                                         @PathVariable Integer baseIdentity) {
        List<Function> functionList = functionService.findByBase(baseId, baseIdentity);
        return new Result(true, StatusCode.OK,"查找基地角色权限成功",functionService.grand(functionList));
    }

    /**
     * 查找可授权给角色的权限
     * @param roleId
     * @return
     */
    @ApiOperation("查找可授权给角色的权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value="/findOtherFunction/{roleId}",method = RequestMethod.GET)
    public Result findFunction(@PathVariable String roleId){
        List<Function> functionList = functionService.findOthersByRoleId(roleId);
        return new Result(true,StatusCode.OK,"查找角色权限成功",functionList);
    }

    /**
     * 更新角色的权限
     * @param roleId
     * @param functionIdList
     * @return
     */
    @ApiOperation("更新角色的权限")
    @PreAuthorize("hasAnyAuthority('authority_role_updateRoleFunction')")
    @RequestMapping(value="/{roleId}",method = RequestMethod.POST)
    public Result UpdateFunOfRole(@PathVariable String roleId ,
                                  @RequestBody
                                  @ApiParam(name = "权限Id集合Map",value = "传入json格式,{\"functionIdList\": [\"1\", \"3\"]}")
                                          Map functionIdList){
        functionService.updateFunctionOfRole(roleId,functionIdList);
        try {
            TimeUnit.MILLISECONDS.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Result.success("更新角色权限成功");
    }


    /**
     * 根据roleId查询基地用户权限
     *
     * @param roleId
     * @return
     */
    public Result findByRoleId(String roleId) {
        if(StringUtils.isEmpty(roleId)) {
            return Result.error("查询失败");
        }
        List<Function> functionLists = functionService.findThroughRoleIdFromFunctionRole(roleId);
        return Result.success().data(functionLists);
    }

    /**
     * 根据角色id查询权限
     * @param roleId
     * @return
     */
    @ApiOperation("根据角色id查询权限")
    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value="/findFunction/{roleId}",method = RequestMethod.GET)
    public Result findFunctionByRoleId(@PathVariable String roleId){
        if(StringUtils.isEmpty(roleId)) {
            return Result.error("角色为空");
        }
        List<Function> functionList = functionService.findByRoleId(roleId);
        return new Result(true,StatusCode.OK,"查找角色权限成功",functionService.grand(functionList));
    }
}

